package com.yyy.saga.service.impl;

import com.yyy.common.dao.AccountDao;
import com.yyy.common.exception.BusinessException;
import com.yyy.saga.dao.TransferTransactionDao;
import com.yyy.saga.entity.TransferTransaction;
import com.yyy.saga.service.TransferService;
import java.math.BigDecimal;
import java.sql.SQLException;

/**
 * Saga模式转账服务实现
 */
public class TransferServiceImpl implements TransferService {
    private AccountDao accountDao = new AccountDao();
    private TransferTransactionDao transactionDao = new TransferTransactionDao();

    @Override
    public boolean transfer(String transactionId, String fromUserId, String toUserId, BigDecimal amount) {
        try {
            // 1. 创建事务记录
            if (!transactionDao.createTransaction(transactionId, fromUserId, toUserId, amount)) {
                throw new BusinessException("SAGA-001", "创建事务记录失败");
            }

            // 2. 扣除转出账户金额
            if (!accountDao.freezeAmount(fromUserId, amount)) {
                transactionDao.updateStatus(transactionId, "FAILED");
                throw new BusinessException("SAGA-002", "扣款失败，余额不足");
            }

            try {
                // 3. 增加转入账户金额
                if (!accountDao.confirmTransfer(fromUserId, toUserId, amount)) {
                    // 如果转入失败，需要补偿
                    compensate(transactionId);
                    throw new BusinessException("SAGA-003", "转入失败");
                }

                // 4. 更新事务状态为成功
                transactionDao.updateStatus(transactionId, "SUCCESS");
                return true;

            } catch (Exception e) {
                // 发生异常，执行补偿
                compensate(transactionId);
                throw new BusinessException("SAGA-004", "转账失败: " + e.getMessage());
            }

        } catch (SQLException e) {
            throw new BusinessException("SAGA-005", "数据库操作失败: " + e.getMessage());
        }
    }

    @Override
    public boolean compensate(String transactionId) {
        try {
            // 1. 查询事务记录
            TransferTransaction transaction = transactionDao.getByTransactionId(transactionId);
            if (transaction == null) {
                throw new BusinessException("SAGA-006", "事务记录不存在");
            }

            // 2. 更新事务状态为补偿中
            transactionDao.updateStatus(transactionId, "COMPENSATING");

            // 3. 返还转出账户金额
            if (!accountDao.cancelFreeze(transaction.getFromUserId(), transaction.getAmount())) {
                throw new BusinessException("SAGA-007", "补偿失败");
            }

            // 4. 更新事务状态为已补偿
            transactionDao.updateStatus(transactionId, "COMPENSATED");

            return true;
        } catch (SQLException e) {
            throw new BusinessException("SAGA-008", "数据库操作失败: " + e.getMessage());
        }
    }
}
